package com.fzl.spring_chatroom.common.advice;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fzl.spring_chatroom.model.response.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import org.springframework.http.converter.HttpMessageConverter;
import java.io.InputStream;

@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice {
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        Class<?> clazz = returnType.getParameterType();
        // 跳过byte[]和InputStream类型
        return !(clazz == byte[].class || InputStream.class.isAssignableFrom(clazz));
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
            Class selectedConverterType,
            ServerHttpRequest request, ServerHttpResponse response) {
        if (body instanceof byte[] || body instanceof InputStream) {
            return body; // 不做包装
        }
        if (body instanceof String) {
            try {
                // 返回String时要返回JSON字符串
                return objectMapper.writeValueAsString(Result.success(body));
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }
        if (body instanceof Result) {
            return body;
        }
        return Result.success(body);
    }
}
